#include <stdio.h>
#include <mosquitto.h>
#include <stdbool.h>
#include <unistd.h>
#include <mysql/mysql.h>
#include <string.h>

typedef struct mosquitto * MQTT_CLIENT;

extern void on_subscribe_callback(struct mosquitto *, void *, int, int, const int *);
extern void on_message_callback(struct mosquitto *, void *, const struct mosquitto_message *);

MYSQL db;
const char *topic = "wifi/dht11/qfxa/00/data";
// ./sub topic
int main(int argc, char const *argv[])
{
    mysql_init(&db);  // 初始化数据库
    if(mysql_real_connect(&db, "localhost","root", "root", "wifidb", 3306, NULL, 0) != NULL){
        printf("mysql connected!\n");
        // mysql_close(&db);
    }else{
        printf("mysql connect fail!\n");
        return -1;
    }

    // 1. 初始化mosquitto库环境
    mosquitto_lib_init();

    // 2. 创建mqtt的客户端
    MQTT_CLIENT client= mosquitto_new("wifi_client_00", false, NULL);

    // 3. 连接服务器
    // host : mqtt服务器的IP  47.97.244.241，  localhost
    if(mosquitto_connect(client, "localhost", 1883, 60) == MOSQ_ERR_SUCCESS){
        // 4. 订阅消息
        // 4.1 设置订阅回调函数
        mosquitto_subscribe_callback_set(client, on_subscribe_callback);
        // 4.2 设置订阅消息的回调
        mosquitto_message_callback_set(client, on_message_callback);

        // 4.3 开始订阅消息
        mosquitto_subscribe(client, NULL, topic, 0);
    }
    // 5. 开始处理网络事件
    // mosquitto_loop();
    while(1){
        mosquitto_loop_start(client);
        usleep(1000); // 1ms
    }

    // 使用完成后， 清除mosquitto库环境
    mosquitto_lib_cleanup();
    return 0;
}

void on_subscribe_callback(struct mosquitto *cli, void *usr_data, int msgid, int qos_cnt, const int *qos){
    printf("---订阅成功--\n");
}

void on_message_callback(struct mosquitto *cli, void *usr_data , const struct mosquitto_message *msg){
    printf("--topic(%s): %s--\n", msg->topic, (char *)msg->payload);
    if(strncmp( msg->topic, topic, strlen(topic)) != 0) return;

    // 将temp,humi 保存到数据库wifidb的dht11表（更新第一行）
    char s[32]= "";
    strncpy(s, (char *)msg->payload, strlen((char *)msg->payload));
    char *temp = strtok(s, ",");
    char *humi = strtok(NULL, ",");

    char sql[128] = "";
    sprintf(sql, "update t_dht11 set temp=%s,humi=%s where id=1", temp, humi);

    int ret = mysql_real_query(&db, sql, strlen(sql));
    printf("--update (%d)--: %s\n", ret, mysql_error(&db));
    
}